'''
Created on Aug 22, 2012

@author: thomas_dao
'''
from datetime import datetime
from entity.entity import Article, Board, Note
from google.appengine.ext import ndb
from kid import util
from operator import attrgetter
from web import settings
import logging
from app import cache_helper

@ndb.tasklet
def get_all(user_key, **q_options):
    qry = Board.query(Board.user == user_key)
    boards = yield qry.fetch_async(**q_options)
    raise ndb.Return(boards)

@ndb.tasklet
def get_notes_by_board(board_key):
    # Get notes from memcache first, if not will query datastore
    notes = cache_helper.get_notes_by_board(board_key)
    
    if notes is None:    
        qry = Note.query(Note.board == board_key).order(-Note.created_time)
        notes = yield qry.fetch_async(settings.BATCH_SIZE)
        # Set notes, curs, more to memcache
        cache_helper.set_notes_by_board(board_key, data=notes)
        
    raise ndb.Return(notes)

@ndb.tasklet
def get_default_board_key(user_key):
    qry = Board.query(Board.user == user_key, Board.name == settings.DEFAULT_BOOKMARK)
    board_key = yield qry.get_async(keys_only=True)
    raise ndb.Return(board_key)

@ndb.tasklet
def get_top_follow(**q_options):
    qry = Board.query().order(-Board.followers_count)
    (boards, cur, more) = yield qry.fetch_page_async(settings.BATCH_SIZE, **q_options)
    raise ndb.Return(boards, cur, more)

@ndb.tasklet
def get_boards_followed_by_user(user_key):
    qry = Board.query(Board.followers==user_key)
    boards = yield qry.fetch_async(keys_only=True)
    raise ndb.Return(boards)